package com.seek.service.imp;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alipay.api.internal.util.StringUtils;
import com.bankfourfactor.BankCarFactorEntity;
import com.bankfourfactor.ResParam;
import com.bankfourfactor.nanyun.NanYunFourFactor;
import com.seek.cache.CacheUtil;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.entity.TBizFlow;
import com.seek.service.BankFourFactorService;
import com.seek.service.BizFlowService;
import com.seek.service.CustomerCardService;
import com.seek.service.CustomerService;
import com.seek.util.BankUtil;
import com.seek.util.CommonUtil;

import net.sf.json.JSONObject;
@Repository("nyBankFourFactorService")
public class NYBankFourFactorServiceImpl implements BankFourFactorService{
	 private   CustomerCardService  customerCardService =  (CustomerCardService)SpringContextHolder.getBean("customerCardService");
	 private  BizFlowService bizFlowService = (BizFlowService)SpringContextHolder.getBean("bizFlowService"); 
	 private  CustomerService customerService = (CustomerService)SpringContextHolder.getBean("customerService"); 
	 private static Logger logger = LoggerFactory.getLogger(NYBankFourFactorServiceImpl.class); 
@Override
//@Transactional(propagation = Propagation.REQUIRES_NEW)
public Map<String, Object> process(Map<String, String> publicParams, BankCarFactorEntity b)  {
	//0:调用失败，1：调用成功，2，调用成功，操作错误 3：没进行调用
	int  processCode = 0;
	String orderNo = "";
	String bizFlowStatus = "0";
	int redisStatus = 3;
	String resJson = "";
	String respCode = "";
	JSONObject json = null;
	Map<String,Object> resultMap = new HashMap<String,Object>();
	String orgName = BankUtil.getNameOfBank(b.getCardNo());
	if(StringUtils.isEmpty(orgName)){
		processCode=3;
	}else{
			Map<String,Object> nyRespMap = null;
		try {
			logger.error("==========================NYBankCarFactorEntity========"+JSON.toJSONString(b));
			nyRespMap = NanYunFourFactor.submitNanYunFactor(b);
		} catch (Exception e) {
			processCode = 0;
		}
		if(MapUtils.isEmpty(nyRespMap)){
			processCode = 0;
		}else{
			 JSONObject nyjson = JSONObject.fromObject(nyRespMap);
			 String status = nyjson.getString("respCode");//认证状态
			 
			 if(status.equals("0000")) {
				 bizFlowStatus = "1";
				 status = "1";
				 redisStatus = 2;
				 processCode=1;
			 }else if(status.startsWith("X")){
				 status = "2";
				 redisStatus = 3;
				 processCode=0;
				 bizFlowStatus = "1";
			 }else{
				 redisStatus = 3;
				 status = "2";
				 processCode=0;
				 bizFlowStatus = "1";
			 }
			 String message = nyjson.getString("respMsg");//认证信息
			 ResParam param = new ResParam();
			 int cardStatus = CommonUtil.getIntValue(publicParams.get("status"))==1?2:3;
			 param.setCode(cardStatus+"");
			 param.setMessage(message);
			 param.setBankName(orgName);
			 String cardNumber = b.getCardNo();
			 param.setCardNo("**** **** ****"+org.apache.commons.lang.StringUtils.substring(cardNumber, cardNumber.length()-4));
			 resultMap.put("param", param);
			 publicParams.put("status", status);
			 publicParams.put("message", message);
		}
		try {
			publicParams.put("orgName", orgName);
			
			
			
			 
			 
			 nyBusicess(publicParams,b);
			 String custToken = CacheUtil.getRedisData("COUSTOMER_TOKEN_" + b.getCustId());  
			 //不知道失败是否刷新缓存
			 Map<String,Object> m = new HashMap<String,Object>();
			 if(publicParams.get("status").equals("2")){
				 m.put("bankName", orgName);
				 m.put("cardNumber", b.getCardNo());
			 }else{
				 m.put("bankName", null);
				 m.put("cardNumber",null);
			 }
			 m.put("cardBindStatus",redisStatus);
			 CacheUtil.refreshCustRedis(custToken, m);
		} catch (Exception e) {
			processCode=2;
		}
		TBizFlow bizFlow = new TBizFlow();
		bizFlow.setCompanyId(CommonUtil.getLongValue(b.getCompanyId()));
		bizFlow.setCustomerId(CommonUtil.getLongValue(b.getCustId()));
		bizFlow.setBizNo(b.getSeq());
		bizFlow.setBizType("银行4要素认证");
		bizFlow.setOrgCode("NANYUN");
		bizFlow.setDeleted(0);
		bizFlow.setOrgBizNo(b.getSeq());
		bizFlow.setStatus(bizFlowStatus);
		bizFlow.setCreateTime(new Date());
		bizFlow.setModifyTime(new Date());
		try {
			bizFlowService.addBizFlow(bizFlow);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	logger.info(processCode+"processCode:{}");
	 resultMap.put("processCode", processCode);
	 return resultMap;
		}
		

@Transactional(propagation = Propagation.REQUIRES_NEW)
public  void  nyBusicess(Map<String,String> publicParams,BankCarFactorEntity b) throws Exception{
	//修改银行卡绑定信息
	 String updateCardSql = "update t_customer_card set audit_status=? , audit_remark=? , audit_time=now(),bank_name=? where  customer_id=? and history=0";
	 customerCardService.executeUpdate(updateCardSql,new Object[]{
			 CommonUtil.getIntValue(publicParams.get("status")),
			 publicParams.get("message"),
			 publicParams.containsKey("orgName")?publicParams.get("orgName"):"",
					b.getCustId()});
	 int cardStatus = CommonUtil.getIntValue(publicParams.get("status"))==1?2:3;
	 String updateCustomerSql = "update t_customer set card_bind_status=? where id = ?";
	 customerService.executeUpdate(updateCustomerSql,new Object[]{cardStatus,CommonUtil.getLongValue(b.getCustId())});
	} 

}
